package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.aliyun.imagesearch20201214.models.SearchImageByPicResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.orm.PageUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.enums.SortOrderEnum;
import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.support.ImageService;
import com.weixing.mall.provider.api.model.dto.SearchItem;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.service.ActivityGoodsRpcService;
import com.weixing.mall.provider.api.service.ProductStockServiceRpc;
import com.weixing.mall.provider.erp.service.ErpService;
import com.weixing.mall.provider.mapper.*;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.GoodsChangeStatusDto;
import com.weixing.mall.provider.model.dto.GoodsDto;
import com.weixing.mall.provider.model.enums.GoodsFromEnum;
import com.weixing.mall.provider.model.enums.GoodsStateEnum;
import com.weixing.mall.provider.model.excel.GoodsED;
import com.weixing.mall.provider.model.query.*;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.service.IGoodsService;
import com.weixing.mall.provider.support.excel.InDepotBillData;
import com.weixing.mall.provider.support.excel.InDepotBillDataListener;
import com.weixing.mall.provider.support.excel.InStockData;
import com.weixing.mall.provider.support.excel.InStocklDataListener;
import com.weixing.mall.util.SKUUtils;
import com.weixing.mall.util.ThreadLocalMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wx
 * @Date 2019/8/9 10:52
 * @Version 1.0
 */

/**
 * <p>
 * 商品模块-商品表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsPartitionMapper goodsPartitionMapper;
    @Autowired
    private GoodsSceneMapper goodsSceneMapper;
    @Autowired
    private GoodsSnMapper goodsSnMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private GoodsImgMapper goodsImgMapper;
    @Autowired
    private GoodsIntroMapper goodsIntroMapper;
    @Autowired
    private GoodsPropMapper goodsPropMapper;
    @Autowired
    private GoodsSpecMapper goodsSpecMapper;
    @Autowired
    private GoodsParamMapper goodsParamMapper;
    @Autowired
    private ActivityGoodsRpcService activityGoodsRpcService;

    @Autowired
    private ProductStockServiceRpc productStockServiceRpc;
    @Autowired
    private ErpService erpService;
    @Autowired
    private GoodsConcernMapper goodsConcernMapper;

    @Autowired
    private WeiXingProperties weiXingProperties;


    private ObjectMapper mapper = new ObjectMapper();


    @Override
    public void delAll(int[] ids) {

        //查询出删除前的状态
        List<GoodsVo> list = baseMapper.selectStatus(ids);
        System.out.println(list.toString());
        //添加删除的时间
        for (int i = 0; i < ids.length; i++) {
            list.get(i).setDeleteTime(new Date());
        }
        //修改删除时间  将状态修改为待删除
        baseMapper.updateStatus(list);
    }


    @Override
    public IPage<GoodsVo> selectOfPage(Page page, GoodsQuery goodsQuery) {
        IPage<GoodsVo> pageList = baseMapper.selectList(page, goodsQuery);
        List<GoodsVo> list = pageList.getRecords();
        //  代码不严谨，不判断集合是否为空
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(GoodsVo::getId).collect(Collectors.toList());
            List<GoodsImg> imgVoList = goodsImgMapper.selectByGoodIds(ids);
            for (GoodsVo goodsVo : list) {
                for (GoodsImg imgVo : imgVoList) {
                    if (goodsVo.getId().longValue() == imgVo.getGoodsId().longValue()) {
                        goodsVo.setGoodsImg(imgVo.getGoodsImg());
                    }
                }
            }
        }

        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<GoodsVo> selectNoPage(GoodsQuery goodsQuery) {
        return baseMapper.selectList(goodsQuery);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(GoodsDto goodsDto) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsDto, goods);

        if (goodsDto.getStatus() != null) {
            goods.setStatus(goodsDto.getStatus().getValue());
        }
        goods.setStatus(GoodsStateEnum.GROUNDING.getValue());
        if (goodsDto.getGoodsSn() != null) {
            goodsDto.setGoodsSn(goodsDto.getGoodsSn().trim());
        }
        if (goodsDto.getStyleNo() != null) {
            goodsDto.setStyleNo(goodsDto.getStyleNo().trim());
        }
        if (null == goodsDto.getId()) {
            if (null != selectByGoodsSn(goodsDto.getGoodsSn())) {
                throw new BusinessException("商品货号已存在");
            }
            if (null != selectByStyleNo(goodsDto.getStyleNo())) {
                throw new BusinessException("商品款号已存在");
            }
            goods.setGoodsFrom(GoodsFromEnum.MANUAL.getValue());
            baseMapper.insert(goods);
        } else {

            updateById(goods);
        }
        //商品新增和修改 先删除商品图片在进行添加
        goodsImgMapper.deleteByGoodsId(goods.getId());
        String[] img = goodsDto.getGoodsImg();
        GoodsImg goodsImg = new GoodsImg();
        for (int i = 0; i < img.length; i++) {
            goodsImg.setGoodsId(goods.getId());
            goodsImg.setGoodsImg(img[i]);
            goodsImg.setOrderBy(i + 1);
            goodsImgMapper.insert(goodsImg);
        }
        //商品场景新增和修改  先删除
        goodsSceneMapper.deleteByGoodsId(goods.getId());
        Long[] sceneId = goodsDto.getSceneId();
        if (ArrayUtil.isNotEmpty(sceneId)) {
            for (int i = 0; i < sceneId.length; i++) {
                GoodsScene goodsScene = new GoodsScene();
                goodsScene.setGoodsId(goods.getId());
                goodsScene.setSceneId(sceneId[i]);
                goodsSceneMapper.insert(goodsScene);
            }
        }

        //商品分区新增和修改  先删除
        goodsPartitionMapper.deleteByGoodsId(goods.getId());
        Integer[] partitionId = goodsDto.getPartitionId();
        for (int i = 0; i < partitionId.length; i++) {
            GoodsPartition goodsPartition = new GoodsPartition();
            goodsPartition.setGoodsId(goods.getId());
            goodsPartition.setPartitionId(partitionId[i]);
            goodsPartitionMapper.insert(goodsPartition);
        }
        return goods.getId();
    }

    @Override
    public void ChangeStatus(GoodsChangeStatusDto goodsChangeStatusDto) {
        Goods goods = getById(goodsChangeStatusDto.getGoodsId());
        goods.setStatus(goodsChangeStatusDto.getGoodsEnum().getValue());
        updateById(goods);
    }

    @Override
    //查询商品基本信息详情

    public GoodsDetailsVo selectById(Long id) {
        //添加用户查看商品足迹
        GoodsDetailsVo goodsDetailsVo = baseMapper.selectDetilById(id);
        List<Integer> partitionId = new ArrayList<>();
        List<Long> sceneId = new ArrayList<>();
        List<String> goodsImg = new ArrayList<>();
        //查询商品图片
        List<GoodsImg> goodsImgList = goodsImgMapper.selectList(id);
        if (goodsImgList.size() > 0) {
            for (int i = 0; i < goodsImgList.size(); i++) {
                goodsImg.add(goodsImgList.get(i).getGoodsImg());
            }
        }
        //查询分区
        List<GoodsPartition> partitionList = goodsPartitionMapper.selectByGoodsId(id);
        if (partitionList.size() > 0) {
            for (GoodsPartition goodsPartition : partitionList) {
                partitionId.add(goodsPartition.getPartitionId());
            }
        }
        //查询场景
        List<GoodsScene> sceneList = goodsSceneMapper.selectByGoodsId(id);
        if (sceneList.size() > 0) {
            for (GoodsScene goodsScene : sceneList) {
                sceneId.add(goodsScene.getSceneId());
            }
        }
        goodsDetailsVo.setSceneId(sceneId);
        goodsDetailsVo.setPartitionId(partitionId);
        goodsDetailsVo.setGoodsImg(goodsImg);
        return goodsDetailsVo;
    }

    @Override
    public IPage<GoodsVo> selectListByIdsPage(Page page, int[] ids) {
        return baseMapper.selectListByIds(page, ids);

    }

    @Override
    public GoodsEsVo selectGoodsSearchVo(long goodsId) {
        return baseMapper.selectGoodsSearchVo(goodsId);
    }

    @Override
    public SearchItem selectItemVo(long goodsId) throws IOException {
        // 商品基本信息
        GoodsEsVo goodsSearchVo = selectGoodsSearchVo(goodsId);
        // 商品图片
        List<String> goodsImg = goodsImgMapper.findGoodsImgByGoodsId(goodsId);
        // 商品场景
        List<String> scenes = goodsSceneMapper.findGoodsSceneByGoodsId(goodsId);
        // SKUs
        List<ProductEsVo> productVos = productMapper.findProductEsByGoodsId(goodsId);
        List<Double> prices = Lists.newArrayList();
        for (ProductEsVo productEsVo : productVos) {
            prices.add(productEsVo.getPrice());
        }
        // specs 可选规格
        Collections.sort(prices);
        SearchItem searchItemVo = new SearchItem();
        BeanUtils.copyProperties(goodsSearchVo, searchItemVo);
        searchItemVo.setPrice(prices);
        searchItemVo.setScenes(mapper.writeValueAsString(scenes));
        searchItemVo.setImgs(mapper.writeValueAsString(goodsImg));
        searchItemVo.setSkus(productVos);
        return searchItemVo;
    }

    @Override
    public List<GoodsPlaceVo> selectGoods(GoodsPlaceOrderQuery goodsPlaceOrderQuery) {
        List<ProductStockVo> tt = Lists.newArrayList();
        if (null != goodsPlaceOrderQuery.getDepotId()) {
            tt = productStockServiceRpc.getAllByDepotId(goodsPlaceOrderQuery.getDepotId());

        }
        //首先根据商品名称，商品货号,分区进行模糊查询如果不匹配在根据商品码再次进行查询
        List<GoodsPlaceVo> list = baseMapper.selectGoods(goodsPlaceOrderQuery);
        if (!list.isEmpty()) {
            for (GoodsPlaceVo goodsPlaceVo : list) {
                List<ItemVo> productVos = productMapper.selectByGoods(goodsPlaceVo.getId());
                ArrayList<GoodsSkuVo> goodsSkuVos = new ArrayList<>();
                for (ItemVo productVo : productVos) {
                    GoodsSkuVo goodsSkuVo = new GoodsSkuVo();
                    goodsSkuVo.setProductId(productVo.getId());
                    goodsSkuVo.setProductSkuDesp(productVo.getProductSkuDesp());
                    goodsSkuVo.setProductSn(productVo.getProductSn());
                    goodsSkuVo.setProductStock(0);
                    for (ProductStockVo stockVo : tt) {
                        if (productVo.getId().equals(stockVo.getProductId())) {
                            goodsSkuVo.setProductStock(stockVo.getStock());
                        }
                    }
                    goodsSkuVos.add(goodsSkuVo);
                    goodsPlaceVo.setProduct(goodsSkuVos);
                }
            }
        } else {
            GoodsPlaceVo goodsPlaceVo = goodsSnMapper.selectByGoodsSn(goodsPlaceOrderQuery.getGoods());
            if (null == goodsPlaceVo) {
                return list;
            }
            goodsPlaceVo.setProductStock(0);
            list.add(goodsPlaceVo);
        }


        return list;
    }

    @Override
    public IPage<GoodsPlaceVo> selectByGoodsInfo(Page page, GoodsPlaceOrderQuery goodsPlaceOrderQuery) {
        //首先根据商品名称，商品货号,分区进行模糊查询如果不匹配在根据商品码再次进行查询
        return baseMapper.selectGoods(page, goodsPlaceOrderQuery);
    }

    @Override
    public IPage hotGoods(Page page, HotGoodsQuery hotGoodsQuery) {
        IPage<FrontGoodsVo> pageList = baseMapper.hotGoods(page, hotGoodsQuery);
        for (FrontGoodsVo frontGoodsVo : pageList.getRecords()) {
            List<String> imgList = goodsImgMapper.findGoodsImgByGoodsId(frontGoodsVo.getId());
            if (imgList.size() > 0) {
                String goodsImg = imgList.get(0);
                frontGoodsVo.setGoodsImg(goodsImg);
            }

        }
        return pageList;
    }

    @Override
    public SpuVo loadModel(Long idN, Long actId, Long mid) {
        // 商品信息
        Goods goods = getById(idN);
        Long goodsId = goods.getId();
        // 商品图片
        List<String> goodsImgList = goodsImgMapper.findGoodsImgByGoodsId(goodsId);

        // 商品详情
        GoodsIntro goodsIntro = goodsIntroMapper.selectByGoodsId(goodsId);
        // 商品属性
        List<SpuPropVo> propList = goodsPropMapper.selectSpuPropbyGoodsId(goodsId);
        // 商品参数
        List<SpuParamVo> paramList = goodsParamMapper.selectSpuParamByGoodsId(goodsId);
        // sku列表
        List<SkuVo> skuVos = productMapper.selectSkuVoByGoodsId(goodsId);
        if (actId != null) {
            // 商品促销信息
            Result<List<ActGoodsVo>> listResult = activityGoodsRpcService.selectByActIdAndGoodsId(goodsId, actId);
            List<ActGoodsVo> data = listResult.getData();
            if(ObjectUtil.isNotNull(data)){


            for (ActGoodsVo ag : data) {
                for (SkuVo skuVo : skuVos) {

                    if (ag.getProductId().equals(skuVo.getId())) {
                        skuVo.setDiscountPrice(ag.getActPrice());
                        skuVo.setProductStock(ag.getProductCount());
                    }
                }
            }
            }
            skuVos = hanlderSku(skuVos, data);//处理商品活动的SKU；
        } else {
            /**
             * 去除已经下架的货品，二期需要调整的业务。
             */
            for (int i = 0; i < skuVos.size(); i++) {
                SkuVo skuVo = skuVos.get(i);
                if (ObjectUtil.isNull(skuVo.getStatus())) {
                    continue;
                }
                if (!skuVo.getStatus().equals(GoodsStateEnum.GROUNDING.getValue())) {
                    skuVos.remove(i);
                    i--;
                }
            }
        }

        // spec
        List<GoodsSpecVo> goodsSpecVos = goodsSpecMapper.selectByGoodsId(goodsId);

        int size = goodsSpecVos.size();
        GoodsSpecVo goodsSpecVo = null;
        List<SpuSpecVo> spuSpecVos = Lists.newArrayList();
        SpuSpecVo spuSpecVo = null;
        for (int i = 0; i < size; i++) {
            goodsSpecVo = goodsSpecVos.get(i);
            spuSpecVo = new SpuSpecVo();
            spuSpecVo.setSpecId(goodsSpecVo.getSpecId());
            spuSpecVo.setSpecName(goodsSpecVo.getSpecName());
            spuSpecVo.setSpecValues(goodsSpecVo.getSpecValueVoList());
            spuSpecVos.add(spuSpecVo);
        }
        //是否收藏
        boolean isCollect = false;
        if (null != mid) {
            isCollect = goodsConcernMapper.selectMyStoreByGoodsIdAndProductId(goodsId, null, mid) > 0 ? true : false;
        }
        // 数据封装
        SpuVo spuVo = new SpuVo();
        spuVo.setGoodsId(goodsId);
        spuVo.setGoodsName(goods.getGoodsName());
        spuVo.setGoodsSn(goods.getGoodsSn());
        spuVo.setDiscountPrice(goods.getDiscountPrice());
        spuVo.setMarketPrice(goods.getMarketPrice());
        spuVo.setExpressType(goods.getExpressType());
        spuVo.setCatId(goods.getCatId());
        spuVo.setCatName(goods.getCatName());
        spuVo.setGoodsIntro(goodsIntro == null ? null : goodsIntro.getGoodsIntro());
        spuVo.setImgs(goodsImgList);
        spuVo.setProps(propList);
        spuVo.setSkus(skuVos);
        spuVo.setSpecs(spuSpecVos);
        spuVo.setParams(paramList);
        spuVo.setIsCollect(isCollect);

        return spuVo;
    }

    private List<SkuVo> hanlderSku(List<SkuVo> skuVos, List<ActGoodsVo> data) {
        for (int i = 0; i < skuVos.size(); i++) {
            SkuVo vo = skuVos.get(i);
            boolean flag = false;
            for (ActGoodsVo actGoodsVo : data) {
                Long proudctId = actGoodsVo.getProductId();
                Integer upDowm = actGoodsVo.getUpDown();
                Integer productCount = actGoodsVo.getProductCount();

                if (vo.getId().equals(proudctId)) {
                    if (upDowm.intValue() != 0 || productCount.intValue() != 0) {//下架或者库存为0 ，直接移除掉
                        flag = true;
                        break;
                    }

                }
            }
            if (!flag) {
                skuVos.remove(i);
                i--;

            }

        }
        return skuVos;
    }

//    @Override
//    public SpuVo loadModelByGoodsSn(Page page, String goodsSn) {
//        Goods goods = selectByGoodsSn(goodsSn);
//        List<Goods> goodsList = list(new QueryWrapper<Goods>().like("goods_sn", goodsSn));
//        IPage goodsPage = page(page, new QueryWrapper<Goods>().like("goods_sn", goodsSn));
//
//        Long goodsId = goods.getId();
//        // 商品图片
//        List<String> goodsImgList = goodsImgMapper.findGoodsImgByGoodsId(goodsId);
//        // 商品详情
//        GoodsIntro goodsIntro = goodsIntroMapper.selectByGoodsId(goodsId);
//        // 商品属性
//        List<SpuPropVo> propList = goodsPropMapper.selectSpuPropbyGoodsId(goodsId);
//        // 商品参数
//        List<SpuParamVo> paramList = goodsParamMapper.selectSpuParamByGoodsId(goodsId);
//        // sku列表
//        List<SkuVo> skuVos = productMapper.selectSkuVoByGoodsId(goodsId);
//
//        // spec
//        List<GoodsSpecVo> goodsSpecVos = goodsSpecMapper.selectByGoodsId(goodsId);
//
//        int size = goodsSpecVos.size();
//        GoodsSpecVo goodsSpecVo = null;
//        List<SpuSpecVo> spuSpecVos = Lists.newArrayList();
//        SpuSpecVo spuSpecVo = null;
//        for (int i = 0; i < size; i++) {
//            goodsSpecVo = goodsSpecVos.get(i);
//            spuSpecVo = new SpuSpecVo();
//            spuSpecVo.setSpecId(goodsSpecVo.getSpecId());
//            spuSpecVo.setSpecName(goodsSpecVo.getSpecName());
//            spuSpecVo.setSpecValues(goodsSpecVo.getSpecValueVoList());
//            spuSpecVos.add(spuSpecVo);
//        }
//        // 数据封装
//        SpuVo spuVo = new SpuVo();
//        spuVo.setGoodsId(goodsId);
//        spuVo.setGoodsName(goods.getGoodsName());
//        spuVo.setGoodsSn(goods.getGoodsSn());
//        spuVo.setCatId(goods.getCatId());
//        spuVo.setCatName(goods.getCatName());
//        spuVo.setGoodsIntro(goodsIntro.getGoodsIntro());
//        spuVo.setImgs(goodsImgList);
//        spuVo.setProps(propList);
//        spuVo.setSkus(skuVos);
//        spuVo.setSpecs(spuSpecVos);
//        spuVo.setParams(paramList);
//        return spuVo;
//    }


    @Override
    public Page<FrontGoodsVo> loadModelByGoodsSn(Page page, String goodsSn) {
        IPage goodsPage = page(page, new QueryWrapper<Goods>().eq("status", GoodsStateEnum.GROUNDING.getValue()).like("goods_sn", goodsSn));
        List<Goods> records = goodsPage.getRecords();
        List<FrontGoodsVo> vos = Lists.newArrayList();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(goods -> {
                FrontGoodsVo goodsVo = new FrontGoodsVo();
                BeanUtils.copyProperties(goods, goodsVo);
                List<String> goodsImgs = goodsImgMapper.findGoodsImgByGoodsId(goods.getId());
                if (CollUtil.isNotEmpty(goodsImgs)) {
                    goodsVo.setGoodsImg(goodsImgs.get(0));
                }
                vos.add(goodsVo);
            });
        }
        return PageUtil.newPage(goodsPage.getCurrent(), goodsPage.getSize(), goodsPage.getTotal(), vos);
    }

    /*
     * 使用说明：价格使用数值，颜色和尺码使用汉字例如 ：“红色"，”XXL",场景和分类使用ID号，参数使用数值
     *
     *
     * */
    @Override
    public IPage<FrontGoodsVo> selectFrontGoods(Page page, FrontGoodsQuery frontGoodsQuery) {
        System.out.println(DateUtil.currentSeconds());
        IPage<FrontGoodsVo> pageList = getQueryList(page, frontGoodsQuery);
        List<FrontGoodsVo> frontGoodsVos = pageList.getRecords();
        //  代码不严谨，不判断集合是否为空
        if (CollUtil.isNotEmpty(frontGoodsVos)) {
            List<Long> ids = frontGoodsVos.stream().map(FrontGoodsVo::getId).collect(Collectors.toList());
            List<GoodsImg> imgVoList = goodsImgMapper.selectByGoodIds(ids);
            for (FrontGoodsVo goodsVo : frontGoodsVos) {
                for (GoodsImg imgVo : imgVoList) {
                    if (goodsVo.getId().longValue() == imgVo.getGoodsId().longValue()) {
                        goodsVo.setGoodsImg(imgVo.getGoodsImg());
                    }
                }
            }
        }

        pageList.setRecords(frontGoodsVos);
       /* System.out.println(DateUtil.currentSeconds());
        if (null != pageList) {
            for (FrontGoodsVo frontGoodsVo : pageList.getRecords()) {
                List<String> imgList = goodsImgMapper.findGoodsImgByGoodsId(frontGoodsVo.getId());
                if (imgList.size() > 0) {
                    String goodsImg = imgList.get(0);
                    frontGoodsVo.setGoodsImg(goodsImg);
                }
            }
        }*/
        System.out.println(DateUtil.currentSeconds());
        return pageList;
    }

    @Override
    public Goods selectByGoodsSn(String goodsSn) {
        Goods goods = baseMapper.selectOne(new QueryWrapper<Goods>().eq("goods_sn", goodsSn));
        return goods;
    }

    @Override
    public Goods checkGoods(String goodsSn, String styleNo) {
        Goods goods = baseMapper.selectOne(new QueryWrapper<Goods>().eq("goods_sn", goodsSn).or().eq("style_no", styleNo));
        return goods;
    }

    public IPage<GoodsVo> selectListByIds(Page page, int[] ids) {
        IPage<GoodsVo> tt = baseMapper.selectListByIds(page, ids);
        return baseMapper.selectListByIds(page, ids);
    }

    @Override
    public List<CategoryVo> findByName(String catName) {
        return categoryMapper.findByName(catName);
    }

    @Override
    public void sortGoods(int sortType) {
        List<Goods> list = baseMapper.selectAllList(sortType);
        if (sortType == SortOrderEnum.SORT_RANDOM.getValue()) {//随机排序
            randomSort(list);
        } else if (sortType == SortOrderEnum.SORT_GOODS.getValue()) {//按照商品的发布时间
            toUpdate(list);
        } else if (sortType == SortOrderEnum.SORT_CLASS.getValue()) {//按照分类排序
            toUpdate(list);
        }
    }

    @Override
    public List<GoodsPlaceVo> listByGoodSn(List<String> goodsSn) {
        List<Goods> list = baseMapper.selectList(new QueryWrapper<Goods>().in("goods_sn", goodsSn));
        List<GoodsPlaceVo> result = Lists.newArrayList();
        for (Goods goods : list) {
            GoodsPlaceVo vo = new GoodsPlaceVo();
            BeanUtils.copyProperties(goods, vo);
            List<ItemVo> productVos = productMapper.selectByGoods(goods.getId());
            ArrayList<GoodsSkuVo> goodsSkuVos = new ArrayList<>();
            for (ItemVo productVo : productVos) {
                GoodsSkuVo goodsSkuVo = new GoodsSkuVo();
                goodsSkuVo.setProductId(productVo.getId());
                goodsSkuVo.setProductSkuDesp(productVo.getProductSkuDesp());
                goodsSkuVo.setProductSn(productVo.getProductSn());
                goodsSkuVos.add(goodsSkuVo);
                vo.setProduct(goodsSkuVos);
            }
        }
        return result;
    }

    /*
     * 出库导入excel处理
     *
     * */
    @Override
    public List<ItemVo> importByOrderSn(MultipartFile file, Long depotId) {
        if (null != file) {
            try {
                EasyExcel.read(file.getInputStream(), InDepotBillData.class, new InDepotBillDataListener(this)).sheet().doRead();
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        List<InDepotBillData> excelGoods = (List<InDepotBillData>) ThreadLocalMap.get("excel_tmp");
        if (excelGoods != null) {
            List<ItemVo> result = coverData(excelGoods, depotId);
            ThreadLocalMap.remove("excel_tmp");
            return result;
        }
        return null;
    }


    private List<ItemVo> coverData(List<InDepotBillData> list, Long depotId) {
        List<ItemVo> result = Lists.newArrayList();
        List<ProductStockVo> checkProductList = productStockServiceRpc.getAllByDepotId(depotId);
        for (InDepotBillData inDepotBillData : list) {
            GoodsQuery query = new GoodsQuery();
            query.setGoodsSn(inDepotBillData.getGoodsSn());
            List<GoodsVo> listGoods = baseMapper.selectList(query);
            if (!list.isEmpty()) {
                for (GoodsVo goods : listGoods) {
                    List<ItemVo> productVos = productMapper.selectByGoods(goods.getId());
                    for (ItemVo productVo : productVos) {
                        for (ProductStockVo checkStockVo : checkProductList) {
                            System.out.println(productVo.getId() + ":" + checkStockVo.getProductId());
                            if (productVo.getId().equals(checkStockVo.getProductId())) {
                                String color = SKUUtils.color(productVo.getProductSkuDesp());
                                String size = SKUUtils.size(productVo.getProductSkuDesp());
                                if (null != inDepotBillData.getColor() && null != inDepotBillData.getSize() && color.equals(inDepotBillData.getColor()) && size.equals((inDepotBillData.getSize()))) {
                                    System.out.println("productVo.getId():" + productVo.getId());
                                    System.out.println("checkStockVo.getProductId():" + checkStockVo.getProductId());
                                    System.out.println(productVo.getProductSkuDesp());
                                    System.out.println(inDepotBillData.getColor());
                                    System.out.println(inDepotBillData.getSize());
                                    productVo.setGoodsSn(goods.getGoodsSn());
                                    productVo.setProductId(productVo.getId());
                                    productVo.setStyleNo(goods.getStyleNo());
                                    productVo.setProductName(goods.getGoodsName());
                                    result.add(productVo);
                                }
                            }
                        }
                    }

                }
            }
        }
        return result;
    }

    private void randomSort(List<Goods> tmp) {
        for (Goods entity : tmp) {
            entity.setOrderNo((long) (Math.random() * 10000));
            baseMapper.updateById(entity);
        }
    }

    private void toUpdate(List<Goods> tmp) {
        for (int i = 0; i < tmp.size(); i++) {
            Goods entity = tmp.get(i);
            entity.setOrderNo((long) i * 100);
            baseMapper.updateById(entity);
        }
    }

    @Override
    public IPage<FrontGoodsVo> selectActFrontGoods(Page page, FrontGoodsQuery frontGoodsQuery) {
        IPage<FrontGoodsVo> pageList = getQueryList(page, frontGoodsQuery);
        if (null != pageList) {
            if (pageList.getRecords() != null) {
                pageList.getRecords().forEach(frontGoodsVo -> {
                    List<GoodsImg> goodsImgList = goodsImgMapper.selectList(frontGoodsVo.getId());
                    if (goodsImgList.size() > 0) {
                        frontGoodsVo.setGoodsImg(goodsImgList.get(0).getGoodsImg());
                    }
                });
            }

        }
        return pageList;
    }

    private IPage<FrontGoodsVo> getQueryList(Page page, FrontGoodsQuery frontGoodsQuery) {
        IPage<FrontGoodsVo> pageList = null;
        if (frontGoodsQuery.getActId() != null) {//如果是活动则去除分区Id
            frontGoodsQuery.setPartitionId(null);
        }
        if (null != frontGoodsQuery.getMaxPrice() || null != frontGoodsQuery.getMinPrice() || null != frontGoodsQuery.getCatId() || null != frontGoodsQuery.getInformation()) {//使用分类和价格搜索以及名称和分类名称
            pageList = baseMapper.findBycatAndPrice(page, frontGoodsQuery);
        } else if (null != frontGoodsQuery.getColorValue() || null != frontGoodsQuery.getSizeValue()) {//按照颜色和尺码
            pageList = baseMapper.findByColorAndSize(page, frontGoodsQuery);
        } else if (null != frontGoodsQuery.getSceneId()) {//按照场景进行搜索
            pageList = baseMapper.findByscene(page, frontGoodsQuery);
        } else if (CollUtil.isNotEmpty(frontGoodsQuery.getParams()) && CollUtil.isNotEmpty(frontGoodsQuery.getParamvalues())) {//按照参数进行搜索
            pageList = baseMapper.findByParameter(page, frontGoodsQuery, frontGoodsQuery.getParams(), frontGoodsQuery.getParamvalues());
        } else {
            pageList = baseMapper.findBycatAndPrice(page, frontGoodsQuery);
        }
        return pageList;
    }

    @Override
    public Goods selectByStyleNo(String styleid) {
        return getOne(new QueryWrapper<Goods>().eq("style_no", styleid));
    }

    /*
     * excel批量导入出库
     *
     * */
    @Override
    public List<ItemVo> importExcelInDepot(MultipartFile file) {
        if (null != file) {
            try {
                EasyExcel.read(file.getInputStream(), InStockData.class, new InStocklDataListener(this)).sheet().doRead();

            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        List<InStockData> excelGoods = (List<InStockData>) ThreadLocalMap.get("excel_tmp");
        if (excelGoods != null) {
            List<ItemVo> result = coverDataItem(excelGoods);
            ThreadLocalMap.remove("excel_tmp");
            return result;
        }

        return null;
    }

    /**
     * 图片搜索服务
     *
     * @param file     文件流
     * @param pageSize 页码
     * @param actId    活动ID
     * @return
     */
    @Override
    public List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> imgSerchList(MultipartFile file, Integer pageSize, Long actId) {
        ImageService imageService = new ImageService();
        List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> result = imageService.search(file, pageSize, weiXingProperties.getAli().getImg());
        if (ObjectUtil.isNull(actId)) {
            return result;
        }
        List<String> ids = result.stream().map(SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions::getProductId).collect(Collectors.toList());
        List<String> productIds = Lists.newArrayList();
        for (String ss : ids) {
            FrontGoodsVo frontGoodsVo = baseMapper.findByImgSearch(actId, ss.split(",")[0]);
            if (ObjectUtil.isNull(frontGoodsVo)) {
                productIds.add(ss);
            }
        }
        if (productIds.size() == 0) {
            return result;
        }
        for (int i = 0; i < result.size(); i++) {
            SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions auctions = result.get(i);
            for (String ss : productIds) {
                if (auctions.getProductId().equals(ss)) {
                    result.remove(i);
                    i--;
                    break;
                }
            }
        }
        try{
        for (int i = 0; i < result.size(); i++) {
            SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions auctions = result.get(i);
            String  goodsId=auctions.getProductId().split(",")[0];
            Goods goods=getById(goodsId);
            if(ObjectUtil.isNotNull(goods.getStatus())&&!goods.getStatus().equals(2)){
                result.remove(i);
                i--;
            }
        }}catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询未上架的SKU信息
     *
     * @param initMpPage 分页信息
     * @param goodsQuery 查询条件
     * @return
     */
    @Override
    public IPage<GoodsVo> selectNoSkuList(Page initMpPage, GoodsQuery goodsQuery) {
        IPage<GoodsVo> pageList = baseMapper.selectNoSkuList(initMpPage, goodsQuery);
        List<GoodsVo> list = pageList.getRecords();
        //  代码不严谨，不判断集合是否为空
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(GoodsVo::getId).collect(Collectors.toList());
            List<GoodsImg> imgVoList = goodsImgMapper.selectByGoodIds(ids);
            for (GoodsVo goodsVo : list) {
                for (GoodsImg imgVo : imgVoList) {
                    if (goodsVo.getId().longValue() == imgVo.getGoodsId().longValue()) {
                        goodsVo.setGoodsImg(imgVo.getGoodsImg());
                    }
                }
            }
        }

        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public void exprotList(GoodsQuery goodsQuery, HttpServletResponse response) throws MalformedURLException {
        IPage<GoodsVo> pageList = baseMapper.selectList(new Page(1, -1), goodsQuery);
        List<GoodsVo> list = pageList.getRecords();
        List<GoodsED> exprotList = Lists.newArrayList();
        //  代码不严谨，不判断集合是否为空
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(GoodsVo::getId).collect(Collectors.toList());
            List<GoodsImg> imgVoList = goodsImgMapper.selectByGoodIds(ids);
            for (GoodsVo goodsVo : list) {
                GoodsED goodsED = new GoodsED();
                BeanUtils.copyProperties(goodsVo, goodsED);
                for (GoodsImg imgVo : imgVoList) {
                    if (goodsVo.getId().longValue() == imgVo.getGoodsId().longValue()) {
                        goodsED.setGoodsImgUrl(new URL(GlobalConstant.IMG_PATH_URL + imgVo.getGoodsImg() + GlobalConstant.IMG_PATH_URL_SUFFIX));
                    }
                    if (goodsVo.getGoodsFrom() != null) {
                        goodsED.setGoodsFrom(goodsVo.getGoodsFrom().getDesp());
                    }
                    if (goodsVo.getStatus() != null && goodsVo.getStatus().intValue() == 2) {
                        goodsED.setStatus("上架");
                    } else {
                        goodsED.setStatus("下架");
                    }
                }
                exprotList.add(goodsED);
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = "售后订单管理列表" + DateUtil.now();
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), GoodsED.class).sheet("sheet1").doWrite(exprotList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<SkuVo> skuList(Long id) {
        Product product = productMapper.selectById(id);
        if (ObjectUtil.isNotNull(product)) {
            Long goodsId = product.getGoodsId();
            List<SkuVo> skuVoList = productMapper.selectSkuVoByGoodsId(goodsId);
            return skuVoList;
        }
        return null;
    }

    @Override
    public List<SkuVo> skuList(Long id, Long actId) {
        Product product = productMapper.selectById(id);
        List<SkuVo> resultList=Lists.newArrayList();
        if (ObjectUtil.isNotNull(product)) {
            Long goodsId = product.getGoodsId();
            try{

                List<SkuVo> skuVoList = productMapper.selectSkuVoByGoodsId(goodsId);
                List<ActGoodsVo> actGoodsVoList=activityGoodsRpcService.selectByActIdAndGoodsId(goodsId,actId).getData();
                for(int i=0;i<skuVoList.size();i++){
                    SkuVo skuVo=skuVoList.get(i);

                    for(ActGoodsVo actGoodsVo1:actGoodsVoList){
                         if(actGoodsVo1.getProductId().equals(skuVo.getId())){
                             resultList.add(skuVo);
                             break;
                         }
                    }

                }
            }catch (Exception e){

            }

        }
        return resultList;
    }

    private List<ItemVo> coverDataItem(List<InStockData> excelGoods) {
        List<ItemVo> result = Lists.newArrayList();
        for (InStockData inDepotBillData : excelGoods) {
            GoodsQuery query = new GoodsQuery();
            query.setGoodsSn(inDepotBillData.getGoodsSn());
            List<GoodsVo> listGoods = baseMapper.selectList(query);
            if (!excelGoods.isEmpty()) {
                for (GoodsVo goods : listGoods) {
                    List<ItemVo> productVos = productMapper.selectByGoods(goods.getId());

                    for (ItemVo productVo : productVos) {
                        if (null != inDepotBillData.getColor() && null != inDepotBillData.getSize() && productVo.getProductSkuDesp().contains(inDepotBillData.getColor()) && productVo.getProductSkuDesp().contains(inDepotBillData.getSize())) {
                            productVo.setGoodsSn(goods.getGoodsSn());
                            productVo.setProductId(productVo.getId());
                            productVo.setStyleNo(goods.getStyleNo());
                            productVo.setProductName(goods.getGoodsName());
                            productVo.setProductStock(inDepotBillData.getNum());
                            result.add(productVo);
                        }

                    }
                }
            }
        }
        return result;
    }

}
